package com.healthcloud.controller.modules.user;

import com.healthcloud.annotation.SysLog;
import com.healthcloud.constants.PagineConsts;
import com.healthcloud.controller.AbstractController;
import com.healthcloud.entity.SysOrganiEntity;
import com.healthcloud.entity.SysRoleEntity;
import com.healthcloud.entity.SysUserEntity;
import com.healthcloud.entity.hospital.SysUserOrganiEntity;
import com.healthcloud.service.hospital.SysOrganiService;
import com.healthcloud.service.SysRoleService;
import com.healthcloud.service.SysUserService;
import com.healthcloud.service.hospital.SysUserOrganiService;
import com.healthcloud.utils.*;
import com.healthcloud.validator.ValidatorUtils;
import com.healthcloud.validator.group.AddGroup;
import com.healthcloud.validator.group.UpdateGroup;

import org.apache.commons.lang.ArrayUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yu on 2017/6/6.
 */
@ApiIgnore
@Controller
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysOrganiService sysOrganiService;
    @Autowired
    private SysUserOrganiService sysUserOrganiService;

    /**
     * 所有用户列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:user:list")
    public String list() {

        return "sys/user/usermgr";

    }


    @RequestMapping("/search")
    @ResponseBody
    public Map<String, Object> searchUser(SysUserEntity entity, Model model, @ModelAttribute("pageParam") PageParam pageParam) {


        //查询列表数据
        if (!getUser().getUsername().equals(Constant.ADMIN)) {
            //非超级管理员
            entity.setId(getUserId());
            entity.setCreateUserId(getUserId());
        }

        List<SysUserEntity> list = sysUserService.search(entity, pageParam);
        int total = sysUserService.queryTotal(entity);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("dataList", list);
        map.put("iTotalRecords", total);
        map.put("iTotalDisplayRecords", total);
        map.put("sEcho", pageParam.getsEcho());
        return map;
    }


    @RequestMapping("/tosave")
    @RequiresPermissions("sys:user:save")
    public String toSave(Model model) {

        PageParam pageParam = new PageParam();
        pageParam.setiDisplayStart(PagineConsts.iDisplayStart);
        pageParam.setiDisplayLength(PagineConsts.iDisplayLength);

        SysRoleEntity entity = new SysRoleEntity();
        //查询列表数据
        if (!getUser().getUsername().equals(Constant.ADMIN)) {
            //超级管理员
            entity.setCreateUserId(getUserId());
        }


        SysOrganiEntity organi = new SysOrganiEntity();
        organi.setType(Constant.WEIJI_ORG_TYPE);
        List<SysOrganiEntity> organis = sysOrganiService.queryList(organi, null);
        List<SysRoleEntity> roleList = sysRoleService.queryList(entity, pageParam);
        model.addAttribute("roleList", roleList);
        model.addAttribute("organis", organis);

        return "sys/user/addOrUpdateUser";
    }

    /**
     * 保存用户
     */
    @SysLog("保存用户")
    @RequestMapping("/save")
    @ResponseBody
    public ApiRes save(SysUserEntity user, Long orgId) {

    	SysUserEntity oldUser = sysUserService.queryByUserName(user.getUsername());
    	if(oldUser != null){
            return new ApiRes(false,null,null,"用户已经存在");
        }
    	
        ValidatorUtils.validateEntity(user, AddGroup.class);

        user.setCreateUserId(getUserId());
        sysUserService.save(user);

        sysUserOrganiService.add(user.getId(), orgId);
        return ApiRes.SUCCESS;
    }


    @RequestMapping("/toupdate")
    @RequiresPermissions("sys:user:update")
    public String toUpdate(@Param("id") String id, Model model) {

        PageParam pageParam = new PageParam();
        pageParam.setiDisplayStart(PagineConsts.iDisplayStart);
        pageParam.setiDisplayLength(PagineConsts.iDisplayLength);

        SysRoleEntity entity = new SysRoleEntity();
        //查询列表数据
        if (!getUser().getUsername().equals(Constant.ADMIN)) {
            //超级管理员
            entity.setCreateUserId(getUserId());
        }

        SysUserEntity user = sysUserService.queryObjectByid(Long.valueOf(id));
        model.addAttribute("entity", user);

        List<SysRoleEntity> roleList = sysRoleService.queryList(entity, pageParam);
        model.addAttribute("roleList", roleList);

        /**
         * 回显机构
         */
        SysUserOrganiEntity userOrgani = sysUserOrganiService.queryByUserId(Long.parseLong(id));
        model.addAttribute("userOrgani", userOrgani);
        SysOrganiEntity organi = new SysOrganiEntity();
        organi.setType(Constant.WEIJI_ORG_TYPE);
        List<SysOrganiEntity> organis = sysOrganiService.queryList(organi, null);
        if (userOrgani!=null){
            for(SysOrganiEntity o : organis){
                if(o.getId()==userOrgani.getOrganiId()){
                    o.setChecked(true);
                }
            }
        }
        model.addAttribute("organis", organis);
        return "sys/user/addOrUpdateUser";
    }

    /**
     * 修改用户
     */
    @SysLog("修改用户")
    @RequestMapping("/update")
    @ResponseBody
    public ApiRes update(SysUserEntity user, Long orgId) {

//    	SysUserEntity oldUser = sysUserService.queryByUserName(user.getUsername());
//    	if(oldUser.getId() != user.getId()){
//            return new JsonMsg(false,null,null,"用户已经存在");
//        }
    	
        ValidatorUtils.validateEntity(user, UpdateGroup.class);

//        user.setCreateUserId(getUserId());
        sysUserService.update(user);
        sysUserOrganiService.add(user.getId(), orgId);
        return ApiRes.SUCCESS;
    }


    /**
     * 删除用户
     */
    @SysLog("删除用户")
    @RequestMapping("/delete")
    @RequiresPermissions("sys:user:delete")
    @ResponseBody
    public ApiRes delete(Long[] userIds) {
        if (ArrayUtils.contains(userIds, Constant.ADMIN)) {
            return new ApiRes(false, null, null, "系统管理员不能删除");
        }

        if (ArrayUtils.contains(userIds, getUserId())) {

            return new ApiRes(false, null, null, "当前用户不能删除");
        }

        /**
         * todo 医生未删除
         */
        sysUserService.deleteBatch(userIds);

        return ApiRes.SUCCESS;
    }

    /**
     * ajax验证登录帐号是否存在
     *
     * @param username 用户名
     * @reurn true:验证通过
     * */
    @RequestMapping(value = "/validateUsername")
    public @ResponseBody Object validateUsername(String username, String exception){

        if(username!=null){
            username = username.toLowerCase();
        }

        Map<String,Boolean> map = new HashMap<>();
        if(username!=null && exception!=null && username.trim().equals(exception.trim())){
            map.put("valid",true);
            return map;
        }
        if(username==null||"".equals(username.trim())){
            map.put("valid",false);
            return map;
        }
        SysUserEntity user = sysUserService.queryByUserName(username);
        if (user==null) {
            map.put("valid",true);
            return map;
        } else {
            map.put("valid",false);
            return map;
        }
    }

    /**
     * ajax验证电话号码是否存在
     *
     * @param mobile 电话号码
     * @reurn true:验证通过
     * */
    @RequestMapping(value = "/validateMobile")
    public @ResponseBody Object validateMobile(String mobile, String exception){
        if(mobile!=null){
            mobile = mobile.toLowerCase();
        }
        Map<String,Boolean> map = new HashMap<>();
        if(mobile!=null && exception!=null && mobile.trim().equals(exception.trim())){
            map.put("valid",true);
            return map;
        }
        if(mobile==null||"".equals(mobile.trim())){
            map.put("valid",false);
            return map;
        }
        SysUserEntity user = sysUserService.queryByMobile(mobile);
        if (user==null) {
            map.put("valid",true);
            return map;
        } else {
            map.put("valid",false);
            return map;
        }
    }

    /**
     * ajax验证邮箱地址是否存在
     *
     * @param email 邮箱地址
     * @reurn true:验证通过
     * */
    @RequestMapping(value = "/validateEmail")
    public @ResponseBody Object validateEmail(String email, String exception){
        Map<String,Boolean> map = new HashMap<>();
        if(email!=null && exception!=null && email.trim().equals(exception.trim())){
            map.put("valid",true);
            return map;
        }
        if(email==null||"".equals(email.trim())){
            map.put("valid",false);
            return map;
        }
        SysUserEntity user = sysUserService.queryByEmail(email);
        if (user==null) {
            map.put("valid",true);
            return map;
        } else {
            map.put("valid",false);
            return map;
        }
    }


    /**
     * 下拉框查询
     */
    @RequestMapping("/select")
    public  @ResponseBody
    ApiRes selectUsername(SysUserEntity bean, @ModelAttribute("pageParam")PageParam pageParam){

        List<SysUserEntity> list = sysUserService.queryList(bean, pageParam);
        int total = sysUserService.queryTotal(bean);
        return new ApiRes(true,list,null,String.valueOf(total));
    }
}
